package com.example.easytts.controller

import com.example.easytts.service.ThreadLocalIpHolder
import com.example.easytts.service.TtsService
import com.example.easytts.service.UserService
import jakarta.servlet.http.HttpServletRequest
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*

@RestController
@RequestMapping("/api/tts")
class TtsController(
    private val ttsService: TtsService,
    private val userService: UserService,
    private val azureTtsService: com.example.easytts.service.AzureTtsService // 新增注入
) {
    data class TtsRequest(
        val text: String,
        val voice: String?,
        val language: String?,
        val useSsml: Boolean?
    )
    
    data class RemainingResponse(
        val remaining: Int
    )

    data class UsageStatResponse(
        val ipTotal: Int,
        val allTotal: Int
    )
    
    @PostMapping("/synthesize")
    fun synthesize(
        @RequestBody request: TtsRequest,
        servletRequest: HttpServletRequest,
        @RequestHeader(value = "Authorization", required = false) authHeader: String?
    ): ResponseEntity<Any> {
        // 验证必要参数
        if (request.voice.isNullOrBlank()) {
            return ResponseEntity.badRequest().body(mapOf(
                "code" to 400,
                "message" to "voice 参数不能为空"
            ))
        }
        if (request.language.isNullOrBlank()) {
            return ResponseEntity.badRequest().body(mapOf(
                "code" to 400,
                "message" to "language 参数不能为空"
            ))
        }
        
        val userId = authHeader?.let { userService.getUserIdFromToken(it) }
        if (userId == null) {
            // 访客，记录IP
            ThreadLocalIpHolder.set(servletRequest.getHeader("X-Forwarded-For")?.split(",")?.get(0)
                ?: servletRequest.remoteAddr)
        }
        val cosUrl = ttsService.synthesizeSpeech(
            text = request.text,
            voice = request.voice,
            language = request.language,
            userId = userId
        )
        return ResponseEntity.ok(mapOf("url" to cosUrl))
    }
    
    @PostMapping("/azure/lrc")
    fun synthesizeWithLrc(
        @RequestBody request: TtsRequest,
        @RequestHeader(value = "Authorization", required = false) authHeader: String?
    ): ResponseEntity<Any> {
        // 验证必要参数
        if (request.voice.isNullOrBlank()) {
            return ResponseEntity.badRequest().body(mapOf(
                "code" to 400,
                "message" to "voice 参数不能为空"
            ))
        }
        if (request.language.isNullOrBlank()) {
            return ResponseEntity.badRequest().body(mapOf(
                "code" to 400,
                "message" to "language 参数不能为空"
            ))
        }
        val userId = authHeader?.let { userService.getUserIdFromToken(it) }
        val isMember = userId != null
        val result = azureTtsService.synthesizeSpeechWithLrc(
            text = request.text,
            voice = request.voice ?: "",
            language = request.language ?: "",
            useSsml = request.useSsml ?: true,
            isMember = isMember
        )
        return ResponseEntity.ok(result)
    }
    
    @GetMapping("/remaining")
    fun getRemainingCharacters(servletRequest: HttpServletRequest): RemainingResponse {
        val clientIp = servletRequest.getHeader("X-Forwarded-For")?.split(",")?.get(0)
            ?: servletRequest.remoteAddr
            
        return RemainingResponse(ttsService.getRemainingCharacters(clientIp))
    }

    @GetMapping("/usage-stat")
    fun getUsageStat(servletRequest: HttpServletRequest): UsageStatResponse {
        val clientIp = servletRequest.getHeader("X-Forwarded-For")?.split(",")?.get(0)
            ?: servletRequest.remoteAddr
        return UsageStatResponse(
            ipTotal = ttsService.getIpTotalCharacters(clientIp),
            allTotal = ttsService.getAllTotalCharacters()
        )
    }
} 